package com.lemon.exam.common.util;

import jakarta.annotation.Resource;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;

/**
 * 发送邮件工具类
 *
 * @author Lemon
 * @since 2025/4/11 15:42
 */
@Slf4j
@Component
public class MailUtil {
    @Resource
    private JavaMailSender mailSender;
    @Resource
    private MailProperties mailProperties;

    @Autowired
    @Qualifier("mailScheduler")
    private Scheduler mailScheduler;

    /**
     * 发送邮件
     *
     * @param to
     * @param subject
     * @param text
     * @param isHtml
     * @return
     */
    public Mono<Void> send(String to, String subject, String text, boolean isHtml) {
        return Mono.fromCallable(() -> {
                    MimeMessage message = mailSender.createMimeMessage();
                    MimeMessageHelper helper = new MimeMessageHelper(message);
                    helper.setFrom(mailProperties.getUsername());
                    helper.setTo(to);
                    helper.setSubject(subject);
                    helper.setText(text, isHtml);
                    return message;
                }).subscribeOn(mailScheduler)
                .flatMap(message -> Mono.fromRunnable(() -> mailSender.send(message)));
    }
}
